package com.zbkj.crmeb.tools.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.constants.Constants;
import com.github.pagehelper.util.StringUtil;
import com.crmeb.core.utils.RedisUtil;
import com.zbkj.crmeb.tools.dao.MoneyExchangeDao;
import com.zbkj.crmeb.tools.model.MoneyExchange;
import com.zbkj.crmeb.tools.service.MoneyExchangeService;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * x
 *
 * @author muyu.myw
 * @date 2020/10/20 15:27
 */
@Slf4j
@Service
public class MoneyExchangeServiceImpl extends ServiceImpl<MoneyExchangeDao, MoneyExchange>
		implements MoneyExchangeService {
	@Value("${tools.exchange.key}")
	String key;
	@Value("${tools.exchange.url}")
	String apiUrl;

	@Autowired
	MoneyExchangeDao moneyExchangeDao;
	@Autowired
	RedisUtil redisUtil;
	
	@Override
	public void syncMoneyExchangeData() {
		// 先获取最新汇率
		log.warn(apiUrl + "?key=" + key);
		String ret = HttpUtil.get(apiUrl + "?key=" + key);
		JSONObject retObj = JSONObject.parseObject(ret);
		// check
		if (!retObj.containsKey("resultcode") || !StringUtils.equals(retObj.getString("resultcode"), "200")) {
			log.error("获取汇率失败! ret={}", ret);
			return;
		}

		// 解析汇率数据
		JSONArray jsonArray = retObj.getJSONArray("result");
		// 更新汇率表
		if (CollectionUtils.isNotEmpty(jsonArray)) {
			jsonArray.forEach(e -> {
				JSONObject obj = (JSONObject) e;
				Collection<Object> dataLi = obj.values();
				if (CollectionUtils.isNotEmpty(dataLi)) {
					dataLi.forEach(o -> {
						JSONObject json = (JSONObject) o;
						MoneyExchange moneyExchange = new MoneyExchange();
						String bankConversionPri = StringUtil.isEmpty(json.getString("bankConversionPri")) ? null : new BigDecimal(json.getString("bankConversionPri")).movePointLeft(2).setScale(4, RoundingMode.UP).toString();
						// 原基础上向上加0.02浮动 取消
						//2023.6.15 改成加0.15
						BigDecimal bankConversionPriBig = new BigDecimal(bankConversionPri).add(new BigDecimal("0.15"));
						bankConversionPri = bankConversionPriBig.toString();
						
						String fBuyPri = StringUtil.isEmpty(json.getString("fBuyPri")) ? null : new BigDecimal(json.getString("fBuyPri")).movePointLeft(2).setScale(4, RoundingMode.UP).toString();
						String mBuyPri = StringUtil.isEmpty(json.getString("mBuyPri")) ? null : new BigDecimal(json.getString("mBuyPri")).movePointLeft(2).setScale(4, RoundingMode.UP).toString();
						String fSellPri = StringUtil.isEmpty(json.getString("fSellPri")) ? null : new BigDecimal(json.getString("fSellPri")).movePointLeft(2).setScale(4, RoundingMode.UP).toString();
						String mSellPri = StringUtil.isEmpty(json.getString("mSellPri")) ? null : new BigDecimal(json.getString("mSellPri")).movePointLeft(2).setScale(4, RoundingMode.UP).toString();
						
						moneyExchange.setName(json.getString("name"));
						moneyExchange.setBankConversionPri(bankConversionPri);
						moneyExchange.setFBuyPri(fBuyPri);
						moneyExchange.setMBuyPri(mBuyPri);
						moneyExchange.setFSellPri(fSellPri);
						moneyExchange.setMSellPri(mSellPri);
						moneyExchange.setDate(json.getString("date"));
						moneyExchange.setTime(json.getString("time"));
						MoneyExchange oldObj = moneyExchangeDao.selectOne(Wrappers.<MoneyExchange>lambdaQuery().eq(MoneyExchange::getName, moneyExchange.getName()));
						if (oldObj != null) {
							moneyExchange.setId(oldObj.getId());
							moneyExchangeDao.updateById(moneyExchange);
						} else {
							moneyExchangeDao.insert(moneyExchange);
						}
						// 加入缓存
						if (Constants.EXCHANGE_EUR_NAME.equals(json.getString("name"))) {
							redisUtil.set(Constants.EXCHANGE_EUR_KEY, bankConversionPri);
						}
					});
				}
			});
		}
	}

	@Override
	public MoneyExchange getExchangeByName(String name) {
		if (StringUtils.isBlank(name)) {
			return null;
		}
		return moneyExchangeDao.selectOne(Wrappers.<MoneyExchange>lambdaQuery().eq(MoneyExchange::getName, name).last("LIMIT 1"));
	}
}
